package com.yeziji.devops.sql.builder;

import cn.hutool.core.util.StrUtil;
import com.yeziji.common.CommonSymbol;
import com.yeziji.devops.common.SqlBuilder;
import com.yeziji.devops.constant.mysql.MysqlKeywordEnum;
import com.yeziji.devops.sql.base.SqlBuilderBase;
import com.yeziji.devops.sql.constructor.SelectSqlConstructor;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.StringJoiner;

/**
 * SQL 查询构造器
 *
 * @author gzkemays
 * @since 2023/01/06 7:38 PM
 */
public class SelectBuilder extends SqlBuilderBase<SelectSqlConstructor> implements SqlBuilder {
    public SelectBuilder() {
    }

    public SelectBuilder(SelectSqlConstructor constructor) {
        super(constructor);
    }

    @Override
    public String execute() {
        List<String> columns = getColumns();
        sqlJoiner.add(getType());
        // 构造查询字段
        if (CollectionUtils.isEmpty(columns)) {
            sqlJoiner.add(MysqlKeywordEnum.ALL_COLUMNS.getValue());
        } else {
            StringJoiner select = new StringJoiner(CommonSymbol.COMMA);
            for (String column : columns) {
                select.add(column);
            }
            sqlJoiner.add(select.toString());
        }
        // 构造表源
        sqlJoiner.add(MysqlKeywordEnum.FROM.getValue()).add(getTable());
        // 构造条件
        String wrapper = getWrapper();
        if (StrUtil.isNotBlank(wrapper)) {
            sqlJoiner.add(MysqlKeywordEnum.WHERE.getValue()).add(wrapper);
        }
        return sqlJoiner.toString();
    }
}
